/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package session3;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

/**
 *
 * @author thanh
 */
public class RegistrationDAO implements Serializable {

    private DBUtils dbUtils;

    public RegistrationDAO() {
    }

    public ArrayList<RegistrationDTO> searchLikeName(String name) {
        boolean check = false;
        Connection conn = null;
        PreparedStatement preSt = null;
        ResultSet rs = null;
        ArrayList result = new ArrayList();
        try {
            conn = dbUtils.makeConnection();
            preSt = conn.prepareStatement("Select * from Resgistration Where Username like ? ");
            preSt.setString(1, "%" + name + "%");
            rs = preSt.executeQuery();
            
            while (rs.next()) {
                String username = rs.getString("Username");
                String password = rs.getString("Password");
                String lastname = rs.getString("Lastname");
                boolean isAdmin = rs.getBoolean("IsAdmin");
                RegistrationDTO dto = new RegistrationDTO(username, password, lastname, isAdmin);
                result.add(dto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (preSt != null) {
                    preSt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }


public boolean checkLogin(String username, String password) {
        boolean check = false;
        Connection conn = null;
        PreparedStatement preSt = null;
        ResultSet rs = null;
        try {
            conn = dbUtils.makeConnection();
            preSt = conn.prepareStatement("Select * from Resgistration Where Username = ? and Password = ? ");
            preSt.setString(1, username);
            preSt.setString(2, password);
            rs = preSt.executeQuery();
            if (rs.next()) {
                check = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(rs!=null)
                    rs.close();
                if(preSt!=null)
                    preSt.close();
                if(conn!=null)
                    conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return check;
    }
}
